import axios from 'axios';
import async from 'async';
import { HOME_INIT, GOODS_INIT, DETAIL_INIT, SUBMIT_ITEM, PAGE_CHANGE } from './actionTypes';

//home
export let getHomeData = (bannerList, goodsList) => {
    return {
        type: HOME_INIT,
        bannerList,
        goodsList
    }
}

export let homeInitAction = dispatch => {
    async.parallel({
        bannerList(cb) {
            axios.get('/static/book.json').then(({ data }) => {
                cb(null, data.banner);
            })
        },
        goodsList(cb) {
            axios.get('/static/book.json').then(({ data }) => {
                cb(null, data.list);
            })
        }
    }, (err, data) => {
        if (!err) {
            dispatch(getHomeData(data.bannerList, data.goodsList));
        }
    })
}

// goods
export let getGoodsData = (goodsList, total) => {
    return {
        type: GOODS_INIT,
        goodsList,
        total        // 总条数
    }
}

export let goodsInitAction = dispatch => {
    axios.get('/static/book.json').then(({ data }) => {
        dispatch(getGoodsData(data.list, data.list.length));
    })
}

export let pageChangeAction = (current) => {
    return dispatch => {
        dispatch({
            type: PAGE_CHANGE,
            current
        });
    }
}



// detail
export let getDetailData = (goods) => {
    return {
        type: DETAIL_INIT,
        goods
    }
}

export let detailInitAction = goodsID => {
    return dispatch => {
        axios.get('/static/book.json').then(({ data }) => {
            let goods = data.list.filter(item => {
                return item.id == goodsID;
            })[0];
            dispatch(getDetailData(goods));
        })
    }
}

// shopping cart



// register
export let setError = (isError) => {
    return {
        type: SUBMIT_ITEM,
        isError
    }
}
export let setErrorAction = (isError) => {
    return dispatch => {
        dispatch(setError(isError))
    }

}



